﻿using System;
using System.Collections.ObjectModel;

using Sunyi.Project.WebPoint.Common;
using Sunyi.Project.WebPoint.DataAccessController;
using Sunyi.Project.WebPoint.DataContract;
using Sunyi.Project.WebPoint.PlatFormException;

namespace Sunyi.Project.WebPoint.BusinessLogic
{
    public partial class SystemInfoServiceManager
    {
        SystemInfoDaoController controller = new SystemInfoDaoController();

        public SystemInfo Select(Guid systemId)
        {
            return controller.Select(systemId);
        }

        public SystemInfo SelectByName(string systemName)
        {
            return controller.SelectByName(systemName);
        }

        public Collection<SystemInfo> SelectAll()
        {
            var systems = controller.Search(string.Empty, true, 0, Int32.MaxValue);

            // TODO
            // It better to return the systems which the current invoker has permission to access.
            // To achieve this logic, it needs a black name list for each specific system.
            // After client system change a user to "disable" status, invoke a service API to add this user in the black name list for the client system.

            return systems;
        }

        public void UpdateSystemInfo(SystemInfo systemInfo, Collection<Role> roles)
        {
            if (systemInfo == null || systemInfo.SystemName == null) ExceptionGenerator.ThrowArgumentNullException("systemInfo");

            var localSystemInfo = controller.Select(systemInfo.Id);

            if (localSystemInfo != null)
            {
                localSystemInfo.Url = systemInfo.Url;
                localSystemInfo.Description = systemInfo.Description;
                localSystemInfo.AutoSignIn = systemInfo.AutoSignIn;
            }

            var roleManager = new RoleManager();
            Collection<Role> newRoles = new Collection<Role>();
            Collection<Role> updateRoles = new Collection<Role>();
            foreach (var role in roles) { if (roleManager.Select(role.Id) == null) newRoles.Add(role); else updateRoles.Add(role); }
            foreach (var removedRole in newRoles) roles.Remove(removedRole);

            Action action = delegate
            {
                if (localSystemInfo != null) controller.Update(localSystemInfo); else controller.Insert(systemInfo);

                foreach (var role in newRoles) roleManager.Insert(role);

                foreach (var role in updateRoles) roleManager.Update(role);
            };

            TransactionHelper.ProcessTransaction(action);
        }
    }
}
